package com.zzty.txj1.controller;

import com.zzty.txj1.entity.User;
import com.zzty.txj1.service.UserService;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    UserService userService;

    @RequestMapping(value = "/checkLogin",method = RequestMethod.POST)
    public Map<String,Object> checkLogin(User user, HttpServletRequest request){
        Map<String,Object> map=new HashMap<>();
        String newPassword = new SimpleHash("md5", user.getPassword(),  ByteSource.Util.bytes(user.getName()), 2).toHex();
        logger.info("newPassword: "+newPassword);
        String pwd=user.getPassword();
        user.setPassword(newPassword);
        User user1=userService.getUserByName(user.getName());
        user1.setPassword1(pwd);
        if(user1==null){
            map.put("result","no");
        }else{
            logger.info("user1: "+user1.toString());
            if(!user.getPassword().equals(user1.getPassword())){
                map.put("result","wrong secret");
            }else{
                HttpSession session=request.getSession();
                session.setAttribute("user",user1);

                if(user1.getType()==null){
                    map.put("result","no type");
                }else{
                    map.put("result",user1.getType());
                }

//                if(user1.getType().equals("1")){
//                    map.put("result","1");
//                }else if(user1.getType().equals("2")){
//                    map.put("result","2");
//                }else if(user1.getType().equals("3")){
//                    map.put("result","3");
//                }else if(user1.getType()==null){
//                    map.put("result","no type");
//                }
            }
        }
        return map;
    }
}
